package com.github.bitsapling.sapling.service.impl;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpInterface;
import com.github.bitsapling.sapling.exception.MyCustomException;
import com.github.bitsapling.sapling.result.ResponseStatusEnum;
import com.github.bitsapling.sapling.entity.Permission;
import com.github.bitsapling.sapling.entity.User;
import com.github.bitsapling.sapling.service.UserGroupService;
import com.github.bitsapling.sapling.service.UserService;
import com.github.bitsapling.sapling.utils.HibernateSessionUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;



@Component
@Slf4j
public class SaTokenPermImpl implements StpInterface {
    @Resource
    private UserService userService;

    @Resource
    private UserGroupService userGroupService;

    @Resource
    private HibernateSessionUtil sessionUtil;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        boolean participate = sessionUtil.bindToThread();
        try {
            User user = userService.getUserById(Long.parseLong(String.valueOf(loginId)));
            if (user == null) {
                throw new MyCustomException(ResponseStatusEnum.UN_LOGIN);
            }
            return userGroupService.getPermissionSlugsById(user.getGroupId());
        }finally {
            sessionUtil.closeFromThread(participate);
        }
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        boolean participate = sessionUtil.bindToThread();
        try {
            User user = userService.getUserById(Long.parseLong(String.valueOf(loginId)));
            if (user == null) {
                throw new MyCustomException(ResponseStatusEnum.UN_LOGIN);
            }
            return List.of(userGroupService.getGroupSlugById(user.getGroupId()));
        }finally {
            sessionUtil.closeFromThread(participate);
        }
    }
}
